package com.intouchtv.ari;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import Servises.FilesManager;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.intouchtv.StartMenu.IconicAdapter;
import com.intouchtv.StartMenu.StartMenuEntry;
import com.intouchtv.ari.R;

public class StartMenuView extends ListActivity {

	public static final String PREFS_NAME = "MyPrefsFile";
	private String url;
	StartMenuEntry[] items;
	private String textFilePath = "http://cs-cinema-workshop.s3.amazonaws.com/NAB/NabStartMenu.txt";
	private static final int MENU_URL = 0;
	private static final int MENU_HELP = 1;
	private static final int CUSTOM_DIALOG = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_view_layout);
		

		final ImageView button = (ImageView) findViewById(R.id.image_button);
		button.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Toast
				.makeText(
						StartMenuView.this,
						"Welcome To MiKiZaZa!\nPlease select one of our featured projects.\n"+
						"Check out mikizaza.wordpress.com for more...",
						Toast.LENGTH_LONG).show();
				return false;
			}
		});

		String textFileLocalPath = "";
		try {
			textFileLocalPath = FilesManager.SaveTempFileFromURL(textFilePath,
					false);
		} catch (Exception e1) {
			Toast
			.makeText(
					StartMenuView.this,
					"Failed to connect to MiKiZaZa server.\n"+
					"Make sure you have WiFi or 3G connection.",
					Toast.LENGTH_LONG).show();
			try {
				Thread.sleep(3500);
			} catch (InterruptedException e) {
				finish();
			}
			finish();
		}

		try {
			populateItemsFromFile(textFileLocalPath);
		} catch (IOException e1) {
			return;
		}

		IconicAdapter adapter = null;

		try {
			adapter = new IconicAdapter(this, items);
		} catch (Exception e) {
			Log.d("dd", e.getMessage());
		}

		setListAdapter(adapter);
	}

	private void populateItemsFromFile(String localPath) throws IOException {
		FileReader fr = new FileReader(localPath);
		String line;
		String[] lineParts;
		ArrayList<StartMenuEntry> entriesList = new ArrayList<StartMenuEntry>();
		BufferedReader in = new BufferedReader(fr);

		if (!in.ready())
			throw new IOException();

		while ((line = in.readLine()) != null) {
			lineParts = line.split("@@@");
			entriesList.add(new StartMenuEntry(lineParts[0], lineParts[1],
					lineParts[2], lineParts[3]));
		}
		in.close();

		items = new StartMenuEntry[entriesList.size()];
		int i = 0;
		for (StartMenuEntry startMenuEntry : entriesList) {
			items[i] = startMenuEntry;
			i++;
		}
	}
	
	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, MENU_URL, 0, "Custom Project");
	    menu.add(0, MENU_HELP, 0, "Help");
	    return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case MENU_URL:
	        showCustomUrlDiag();
	        return true;
	    case MENU_HELP:
			Toast
			.makeText(
					StartMenuView.this,
					"Welcome To MiKiZaZa!\nPlease select one of our featured projects.\n"+
					"Check out mikizaza.wordpress.com for more...",
					Toast.LENGTH_LONG).show();
	        return true;
	    }
	    return false;
	}
	
	private void showCustomUrlDiag()
	{
		try{
			showDialog(CUSTOM_DIALOG);
		}
		catch(Exception e)
		{
			return;
		}
	}
	
	protected Dialog onCreateDialog(int id) {
		if (id == CUSTOM_DIALOG)
			return createCustomUrlDiag();
		return null;
	}
	
	private Dialog createCustomUrlDiag()
	{
		Context mContext = getApplicationContext();
		Dialog dialog = new Dialog(this);

		dialog.setContentView(R.layout.custom_url_dialog_layout);
		dialog.setTitle("Custom Project URL:");

		final EditText edittext = (EditText) dialog.findViewById(R.id.edittext);
		
		edittext.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					url = edittext.getText().toString();
					return true;
				}
				return false;
			}
		});

		final Button startButton = (Button) dialog.findViewById(R.id.start_button);
		startButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				url = edittext.getText().toString();
				startGame(getApplicationContext(), url);
			}
		});
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		url = settings.getString("url", "http://fest.tau.ac.il/mnm/e/E10OLH1.xml");
		edittext.setText(url);
		
		return dialog;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		startGame(getApplicationContext(), items[position].xmlUrl);
	}

	private void startGame(Context c, String url) {
		try {
			Intent myIntent = new Intent(c, NabDemoView.class);
			myIntent.setData(Uri.parse(url));
			startActivity(myIntent);
			// finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();

		// Save user preferences. We need an Editor object to
		// make changes. All objects are from android.context.Context
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("url", url);

		// Don't forget to commit your edits!!!
		editor.commit();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
